package pers.zb.center.web.boss.controller.task;

import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.thread.ExecutorRegistryThread;
import com.xxl.job.core.util.IpUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.zb.center.common.core.util.JsonUtil;
import pers.zb.center.common.core.util.StringUtil;
import pers.zb.center.common.core.vo.JQDatatableResult;
import pers.zb.center.common.core.vo.Pager;
import pers.zb.center.service.user.vo.sys.AppVo;
import pers.zb.center.web.boss.controller.task.handler.TaskVo;
import pers.zb.center.web.boss.controller.task.handler.annotation.JobInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.xxl.job.core.executor.XxlJobExecutor.loadJobHandler;
import static com.xxl.job.core.executor.XxlJobExecutor.registJobHandler;


/**
 * 分布式任务
 *      【分布式任务调度平台】在网上有很多开源的案例，这里我采用的是开源中国上的项目【XXL-JOB】，项目源码地址：https://gitee.com/xuxueli0323/xxl-job
 * 
 * @author zhoubang
 *
 */
@Controller
@RequestMapping("/task")
public class TaskController  implements ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(getClass());


    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 分布式任务调度平台的访问地址
     */
    @Value("#{configProperties['xxl.job.admin.addresses']}")
    private String platformUrl;

    /**
     * 任务的执行日志所在目录
     */
    @Value("#{configProperties['xxl.job.executor.logpath']}")
    private String jobExecutorLogpath;

    /**
     * 执行器应用名称（建议与项目名称一致，方便区分与管理）
     */
    @Value("#{configProperties['xxl.job.executor.appname']}")
    private String jobExecutorAppName;
    /**
     * 执行器应用的IP地址
     */
    @Value("#{configProperties['xxl.job.executor.ip']}")
    private String jobExecutorIp;
    /**
     * 执行器应用的端口号
     */
    @Value("#{configProperties['xxl.job.executor.port']}")
    private int jobExecutoPort;

    /**
     * 进入分布式任务调度平台的页面
     */
    @RequestMapping("/platform/view")
    @RequiresPermissions("task:platform:view")
    public String listView(ModelMap model) {
        model.put("platformUrl",platformUrl);
        return "/task/platform_view_xxljob";
    }

    /**
     * 进入任务列表页面
     * @return
     */
    @RequestMapping("/view/list")
    @RequiresPermissions("task:list")
    public String toTaskListView() {
        return "/task/list";
    }

    /**
     * 定时任务列表
     *
     * 创建日期：2017年9月8日 下午11:23:52 操作用户：zhoubang
     *
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("task:list")
    @ResponseBody
    public JQDatatableResult<TaskVo> taskListView(@ModelAttribute Pager<TaskVo> pager) {
        //反射获取拥有@JobHandler注解的执行器bean
        Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(JobHandler.class);

        //存放集合列表
        List<TaskVo> taskList = null;

        if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
            taskList = new ArrayList<TaskVo>();

            if(StringUtil.isBlank(jobExecutorIp)){
                jobExecutorIp = IpUtil.getIpPort(jobExecutoPort);//这里获取的值，是IP + PORT 的拼接
            }
            for (Object serviceBean : serviceBeanMap.values()) {
                //初始化任务对象VO
                TaskVo vo = new TaskVo(platformUrl,jobExecutorLogpath,jobExecutorAppName,jobExecutorIp,jobExecutoPort, ExecutorRegistryThread.getInstance().getExecutorOnlineStatus());


                if (serviceBean instanceof IJobHandler){//反射获取实现了IJobHandler接口的执行器bean
                    JobHandler jobHandlerClas = serviceBean.getClass().getAnnotation(JobHandler.class);//获取每个bean对应的JobHandler注解对象信息
                    JobInfo jobInfoClas = serviceBean.getClass().getAnnotation(JobInfo.class);//获取每个bean对应的JobInfo注解对象信息

                    String handlerName = jobHandlerClas.value();//执行器名称
                    String jobInfo = jobInfoClas.des();//任务描述
                    String jobName = jobInfoClas.name();//任务名称
                    boolean onlineRun = jobInfoClas.onlineRun();//任务在线上环境是否执行

                    vo.setBeanName(handlerName);
                    vo.setTaskDesc(jobInfo);
                    vo.setTaskName(jobName);
                    vo.setOnlineRun(onlineRun);
                    taskList.add(vo);//将任务加入集合
                }
            }
        }

        JQDatatableResult<TaskVo> result = new JQDatatableResult<TaskVo>();
        result.setData(taskList);
        result.setRecordsTotal(taskList == null ? 0 : taskList.size());
        result.setDraw(pager.getDraw());
        result.setRecordsFiltered(taskList == null ? 0 : taskList.size());
        return result;
    }



}
